<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/yuwanzi.io/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/yuwanzi.io/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/yuwanzi.io/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/yuwanzi.io/images/logo.svg" color="#222">

<link rel="stylesheet" href="/yuwanzi.io/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"suyuhuan.gitee.io","root":"/yuwanzi.io/","images":"/yuwanzi.io/images","scheme":"Muse","version":"8.2.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Suche...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}};
  </script>
<meta name="description" content="概述 B树(B-Tree)是一种自平衡的树,能够保证数据有序.同时它还保证了在查找、插入、删除等操作时性能都能保持在$O(log;n)$.需要注意的一点是,B-Tree并不是一棵自平衡的二叉查找树,它拥有多个分叉,且为大块数据的读写操作做了优化,同时它也可以用来描述外部存储(支持对保存在磁盘或者网络上的符号表进行外部查找). 在当今的互联网环境下,数据量已经大到无法想象,而能够在巨型数据集合中快速">
<meta property="og:type" content="article">
<meta property="og:title" content="B树的那点事儿">
<meta property="og:url" content="https://suyuhuan.gitee.io/yuwanzi.io/2017/08/13/2017-08-13-BTrees/index.html">
<meta property="og:site_name" content="玉丸子 | Blog">
<meta property="og:description" content="概述 B树(B-Tree)是一种自平衡的树,能够保证数据有序.同时它还保证了在查找、插入、删除等操作时性能都能保持在$O(log;n)$.需要注意的一点是,B-Tree并不是一棵自平衡的二叉查找树,它拥有多个分叉,且为大块数据的读写操作做了优化,同时它也可以用来描述外部存储(支持对保存在磁盘或者网络上的符号表进行外部查找). 在当今的互联网环境下,数据量已经大到无法想象,而能够在巨型数据集合中快速">
<meta property="og:locale">
<meta property="og:image" content="http://wx3.sinaimg.cn/large/63503acbly1fihx6539d3j21kw0m9adu.jpg">
<meta property="article:published_time" content="2017-08-13T04:00:00.000Z">
<meta property="article:modified_time" content="2020-11-07T00:58:17.000Z">
<meta property="article:author" content="玉丸子">
<meta property="article:tag" content="2017">
<meta property="article:tag" content="Algorithms">
<meta property="article:tag" content="Tree">
<meta property="article:tag" content="数据结构">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://wx3.sinaimg.cn/large/63503acbly1fihx6539d3j21kw0m9adu.jpg">


<link rel="canonical" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/08/13/2017-08-13-BTrees/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh'
  };
</script>
<title>B树的那点事儿 | 玉丸子 | Blog</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/yuwanzi.io/atom.xml" title="玉丸子 | Blog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Navigationsleiste an/ausschalten" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/yuwanzi.io/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">玉丸子 | Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Inhaltsverzeichnis
        </li>
        <li class="sidebar-nav-overview">
          Übersicht
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-number">1.</span> <span class="nav-text">概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%95%B0%E6%8D%AE%E8%A1%A8%E7%A4%BA"><span class="nav-number">2.</span> <span class="nav-text">数据表示</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9F%A5%E6%89%BE"><span class="nav-number">3.</span> <span class="nav-text">查找</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8F%92%E5%85%A5"><span class="nav-number">4.</span> <span class="nav-text">插入</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E6%96%87%E7%8C%AE"><span class="nav-number">5.</span> <span class="nav-text">参考文献</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">玉丸子</p>
  <div class="site-description" itemprop="description">这里是玉丸子的个人博客,与你一起发现更大的世界。</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/yuwanzi.io/archives">
          <span class="site-state-item-count">68</span>
          <span class="site-state-item-name">Artikel</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/yuwanzi.io/categories/">
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">Kategorien</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/yuwanzi.io/tags/">
        <span class="site-state-item-count">46</span>
        <span class="site-state-item-name">schlagwörter</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/08/13/2017-08-13-BTrees/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          B树的那点事儿
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-08-13 12:00:00" itemprop="dateCreated datePublished" datetime="2017-08-13T12:00:00+08:00">2017-08-13</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/" itemprop="url" rel="index"><span itemprop="name">Algorithms</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" itemprop="url" rel="index"><span itemprop="name">数据结构</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/Tree/" itemprop="url" rel="index"><span itemprop="name">Tree</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><hr>
<p>B树(<code>B-Tree</code>)是一种自平衡的树,能够保证数据有序.同时它还保证了在查找、插入、删除等操作时性能都能保持在$O(log;n)$.需要注意的一点是,<strong><code>B-Tree</code>并不是一棵自平衡的二叉查找树,它拥有多个分叉,且为大块数据的读写操作做了优化,同时它也可以用来描述外部存储(支持对保存在磁盘或者网络上的符号表进行外部查找).</strong></p>
<p>在当今的互联网环境下,数据量已经大到无法想象,而能够在巨型数据集合中快速地进行查找操作是非常重要的,而<code>B-Tree</code>的神奇之处正在于: 只需要使用4~5个指向一小块数据的引用即可有效支持在数百亿甚至更多元素的符号表中进行查找和插入等操作.</p>
<p><code>B-Tree</code>的主要应用在于文件系统与数据库系统,例如<code>Mysql</code>中的<code>InnoDB</code>存储引擎就使用到了<code>B-Tree</code>来实现索引.</p>
<blockquote>
<p>本文作者为: <a target="_blank" rel="noopener" href="https://github.com/SylvanasSun">SylvanasSun</a>.转载请务必将下面这段话置于文章开头处(保留超链接).<br>本文转发自<a target="_blank" rel="noopener" href="https://sylvanassun.github.io/">SylvanasSun Blog</a>,原文链接: <a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/08/13/2017-08-13-BTrees/">https://sylvanassun.github.io/2017/08/13/2017-08-13-BTrees/</a></p>
</blockquote>
<h3 id="数据表示"><a href="#数据表示" class="headerlink" title="数据表示"></a>数据表示</h3><hr>
<p>我们使用页来表示一块连续的数据,访问一页的数据需要将它读入本地内存.一个页可能是本地计算机上的一个文件,也可能是服务器上的某个文件的一部分等等.页的访问次数(无论读写)即是外部查找算法的成本模型.</p>
<p>首先,构造一棵<code>B-Tree</code><strong>不会将数据保存在树中</strong>,而是会构造一棵<strong>由键的副本组成的树,每个副本都关联着一条链接</strong>.这种方法能够将索引与符号表进行分离,同时我们还需要遵循以下的规定: </p>
<ul>
<li>选择一个参数<code>M</code>来构造一棵多向树(<code>M</code>一般为偶数),每个节点最多含有<code>M - 1</code>对键和链接.</li>
</ul>
<ul>
<li>每个节点最少含有<code>M / 2</code>对键和链接,根节点例外(它最少可以含有2对).</li>
</ul>
<ul>
<li>.使用<code>M</code>阶的<code>B-Tree</code>来指定<code>M</code>的值,例如: 在一棵4阶<code>B-Tree</code>中,每个节点都含有至少2对至多3对.</li>
</ul>
<ul>
<li><code>B-Tree</code>含有两种不同类型的节点,内部节点与外部节点.</li>
</ul>
<ul>
<li>内部节点含有与页相关联的键的副本: 每个键都与一个节点相关联(一条链接),以此节点为根的子树中,所有的键都大于等于与此节点关联的键,但小于原内部节点中更大的键(如果存在的话).</li>
</ul>
<ul>
<li>外部节点含有指向实际数据的引用: 每个键都对应着实际的值,外部节点就是一张普通的符号表.</li>
</ul>
<p><img src="http://wx3.sinaimg.cn/large/63503acbly1fihx6539d3j21kw0m9adu.jpg"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// max children per B-tree node = M - 1</span></span><br><span class="line"><span class="comment">// must be even and greater than 2</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> M = <span class="number">4</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// root of the B-tree</span></span><br><span class="line"><span class="keyword">private</span> Node root;</span><br><span class="line"></span><br><span class="line"><span class="comment">// height of the B-tree</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> height;</span><br><span class="line"></span><br><span class="line"><span class="comment">// number of key-value paris int the B-tree</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> N;</span><br><span class="line"></span><br><span class="line"><span class="comment">// B-tree node data type</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> children_length;</span><br><span class="line">	<span class="keyword">private</span> Entry[] children = <span class="keyword">new</span> Entry[M];</span><br><span class="line"></span><br><span class="line">	<span class="comment">// create a node with k children</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">Node</span><span class="params">(<span class="keyword">int</span> k)</span> </span>&#123;</span><br><span class="line">		children_length = k;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// internal nodes : only use key and next</span></span><br><span class="line"><span class="comment">// external nodes : only use key and value</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Entry</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> Comparable key;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">final</span> Object value;</span><br><span class="line">	<span class="keyword">private</span> Node next;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="title">Entry</span><span class="params">(Comparable key, Object value, Node next)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.key = key;</span><br><span class="line">		<span class="keyword">this</span>.value = value;</span><br><span class="line">		<span class="keyword">this</span>.next = next;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="查找"><a href="#查找" class="headerlink" title="查找"></a>查找</h3><hr>
<p>在<code>B-Tree</code>中进行查找操作每次都会结束于一个外部节点.在查找时,<strong>从根节点开始,根据被查找的键来选择当前节点中的适当区间并根据对应的链接从一个节点移动到下一层节点</strong>.最终,查找过程会到达树底的一个含有键的页(也就是外部节点),如果被查找的键在该页中,查找命中并结束,如果不在,则查找未命中.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Value <span class="title">get</span><span class="params">(Key key)</span> </span>&#123;</span><br><span class="line">	validateKey(key, <span class="string">&quot;argument key to get() is null.&quot;</span>);</span><br><span class="line">	<span class="keyword">return</span> search(root, key, height);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> Value <span class="title">search</span><span class="params">(Node x, Key key, <span class="keyword">int</span> height)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">while</span> (x != <span class="keyword">null</span>) &#123;</span><br><span class="line">		Entry[] children = x.children;</span><br><span class="line">		<span class="keyword">int</span> children_length = x.children_length;</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 当树的高度已经递减为0时,也就到达了树的底部(一个外部节点)</span></span><br><span class="line">		<span class="comment">// 遍历当前节点的每个键进行比较,如果找到则查找命中返回对应的值.</span></span><br><span class="line">		<span class="keyword">if</span> (height == <span class="number">0</span>) &#123;</span><br><span class="line">			<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; children_length; j++) &#123;</span><br><span class="line">				<span class="keyword">if</span> (eq(key, children[j].key))</span><br><span class="line">					<span class="keyword">return</span> (Value) children[j].value;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="comment">// 当还是内部节点时,根据键来查找适当的区间</span></span><br><span class="line">			<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; children_length; j++) &#123;</span><br><span class="line">				<span class="keyword">if</span> (j + <span class="number">1</span> == children_length || less(key, children[j + <span class="number">1</span>].key)) &#123;</span><br><span class="line">					<span class="comment">// 找到适当的区间后,移动到下一层节点</span></span><br><span class="line">					x = children[j].next;</span><br><span class="line">					height--;</span><br><span class="line">					<span class="keyword">break</span>;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="插入"><a href="#插入" class="headerlink" title="插入"></a>插入</h3><hr>
<p>插入操作也要先从根节点不断递归地查找到合适的区间,但需要注意一点,如果查找到的外部节点已经满了怎么办呢?</p>
<p>解决方法也很简单,我们允许被插入的节点暂时”溢出”,然后在递归调用自底向上不断地进行分裂.例如:当<code>M</code>为5时,根节点溢出为<code>6-节点</code>,只需要将它分裂为连接了两个<code>3-节点</code>的<code>2-节点</code>.即将一个<code>M-</code>的父节点<code>k</code>分裂为连接着两个<code>(M / 2)-</code>节点的<code>(k + 1)-</code>节点.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">put</span><span class="params">(Key key, Value value)</span> </span>&#123;</span><br><span class="line">	validateKey(key, <span class="string">&quot;argument key to put() is null.&quot;</span>);</span><br><span class="line"></span><br><span class="line">	Node u = insert(root, key, value, height);</span><br><span class="line">	N++;</span><br><span class="line">	<span class="keyword">if</span> (u == <span class="keyword">null</span>)</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// need to split root</span></span><br><span class="line">	Node t = <span class="keyword">new</span> Node(<span class="number">2</span>);</span><br><span class="line">	t.children[<span class="number">0</span>] = <span class="keyword">new</span> Entry(root.children[<span class="number">0</span>].key, <span class="keyword">null</span>, root);</span><br><span class="line">	t.children[<span class="number">1</span>] = <span class="keyword">new</span> Entry(u.children[<span class="number">0</span>].key, <span class="keyword">null</span>, u);</span><br><span class="line">	root = t;</span><br><span class="line">	height++;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> Node <span class="title">insert</span><span class="params">(Node x, Key key, Value value, <span class="keyword">int</span> height)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span> j;</span><br><span class="line">	Entry t = <span class="keyword">new</span> Entry(key, value, <span class="keyword">null</span>);</span><br><span class="line">	Entry[] children = x.children;</span><br><span class="line">	<span class="keyword">int</span> children_length = x.children_length;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// external node</span></span><br><span class="line">	<span class="keyword">if</span> (height == <span class="number">0</span>) &#123;</span><br><span class="line">		<span class="keyword">for</span> (j = <span class="number">0</span>; j &lt; children_length; j++) &#123;</span><br><span class="line">			<span class="keyword">if</span> (less(key, children[j].key))</span><br><span class="line">				<span class="keyword">break</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="comment">// internal node</span></span><br><span class="line">		<span class="keyword">for</span> (j = <span class="number">0</span>; j &lt; children_length; j++) &#123;</span><br><span class="line">			<span class="keyword">if</span> (j + <span class="number">1</span> == children_length || less(key, children[j + <span class="number">1</span>].key)) &#123;</span><br><span class="line">				<span class="comment">// 找到合适的区间后继续递归调用</span></span><br><span class="line">				Node u = insert(children[j++].next, key, value, height - <span class="number">1</span>);</span><br><span class="line">				<span class="comment">// 如果下一层没有进行过分裂操作,直接返回null</span></span><br><span class="line">				<span class="keyword">if</span> (u == <span class="keyword">null</span>)</span><br><span class="line">					<span class="keyword">return</span> <span class="keyword">null</span>;	</span><br><span class="line">				t.key = u.children[<span class="number">0</span>].key;</span><br><span class="line">				t.next = u;</span><br><span class="line">				<span class="keyword">break</span>;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 将j之后的元素全部右移(为了腾出j的插入位置)</span></span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = children_length; i &gt; j; i--) &#123;</span><br><span class="line">		children[i] = children[i - <span class="number">1</span>];</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	children[j] = t;</span><br><span class="line">	x.children_length++;</span><br><span class="line">	<span class="keyword">if</span> (x.children_length &lt; M)</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">else</span></span><br><span class="line">		<span class="keyword">return</span> split(x); <span class="comment">// 如果空间已满,进行分裂</span></span><br><span class="line">&#125;	</span><br><span class="line"></span><br><span class="line"> <span class="comment">// 将x分裂为两个含有new_length对键的节点</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> Node <span class="title">split</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">int</span> new_length = M / <span class="number">2</span>;</span><br><span class="line">	Node t = <span class="keyword">new</span> Node(new_length);</span><br><span class="line">	x.children_length = new_length;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; new_length; j++)</span><br><span class="line">		t.children[j] = x.children[new_length + j];</span><br><span class="line">	<span class="keyword">return</span> t;</span><br><span class="line">&#125;	</span><br></pre></td></tr></table></figure>

<h3 id="参考文献"><a href="#参考文献" class="headerlink" title="参考文献"></a>参考文献</h3><hr>
<ul>
<li><a target="_blank" rel="noopener" href="http://algs4.cs.princeton.edu/home/">Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/B-tree">B-tree - Wikipedia</a></li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/yuwanzi.io/tags/2017/" rel="tag"># 2017</a>
              <a href="/yuwanzi.io/tags/Algorithms/" rel="tag"># Algorithms</a>
              <a href="/yuwanzi.io/tags/Tree/" rel="tag"># Tree</a>
              <a href="/yuwanzi.io/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" rel="tag"># 数据结构</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2017/08/06/2017-08-06-DigestHttps/" rel="prev" title="揭秘HTTPS的"秘密"">
                  <i class="fa fa-chevron-left"></i> 揭秘HTTPS的"秘密"
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2017/08/20/2017-08-20-Encode/" rel="next" title="编码的那点事儿">
                  编码的那点事儿 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">玉丸子</span>
</div>
  <div class="powered-by">Erstellt mit  <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a>
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/yuwanzi.io/js/utils.js"></script><script src="/yuwanzi.io/js/motion.js"></script><script src="/yuwanzi.io/js/schemes/muse.js"></script><script src="/yuwanzi.io/js/next-boot.js"></script>

  






  





</body>
</html>
